#!/usr/bin/env python

# Build CJK Font Package, in tar.bz2 for format

import sys, os, tarfile, time, re, stat

file_map  = { }
INFO_FILE_NAME = "_FONTINFO"
LIST_FILE_NAME = "_FILELIST"
PKG_FILE_EXT   = "fpkg"
EXTRA_INFO_FILE_NAME = "_EXTRAINFO"

file_patterns = { "uni%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-UTF8",\
                  "gbk%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-GBK", \
                  "\w+\.map"                               : "map",    \
                  "\w+\.fd"                                : "fd" }

compiled_exps = { }

def add_to_map(key, file):
    if not file_map.has_key(key):
        file_map[key] = [ ];

    file_map[key].append(file)

def die(str):
    print str
    sys.exit(1)

app_name = sys.argv[0]
if len(sys.argv) < 3:
    die("usage: %s <dir> <font>" % app_name)

dir_name = sys.argv[1]
if dir_name.endswith("/"):
    dir_name = dirname[:-1]

fnt_name = sys.argv[2]
enc_list = [ "uni", "gbk", "big5" ]

if not os.path.isdir(dir_name): 
    die("%s: directory %s not exist." % (app_name, dir_name))

pkg_file_name = "%s.%s" % (fnt_name, PKG_FILE_EXT)
print "building package %s from %s/ for font %s:\n" % \
        (pkg_file_name, dir_name, fnt_name)

# create real mappings
for pat in file_patterns.keys():
    val = file_patterns.pop(pat)
    pat = pat.replace("%FONT%", fnt_name)

    # print "set", pat, "as", val
    file_patterns[pat] = val
    exp = re.compile(pat)
    compiled_exps[pat] = exp

file_list = os.listdir(dir_name)

for file in file_list:
    for pat in file_patterns.keys():
        m = compiled_exps[pat].match(file)
        if m:
            key = file_patterns[pat]
            i   = 1

            # do replacement for #0, #1, #2, ...
            for group in m.groups():
                key = key.replace("#%d" % i, group)
                i += 1

            add_to_map(key, file)
            break

# create info file
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "w")

time_info = time.localtime(time.time())
pkg_date = "%s-%s-%s %s:%s:%s" % (time_info[0], time_info[1], \
                                  time_info[2], time_info[3], \
                                  time_info[4], time_info[4])

info_file.write("font_unique_name: %s\n" % fnt_name)
info_file.write("font_packaged_on: %s\n" % pkg_date)

if os.getenv("FONTMAN_PACKAGER") != None:
    info_file.write("font_packaged_by: %s\n" % os.getenv("FONTMAN_PACKAGER"))

ei_name = "%s/%s" % (dir_name, EXTRA_INFO_FILE_NAME)

if os.path.isfile(ei_name):
    extra_info_file = open(ei_name)
    info_file.write(extra_info_file.read())
    extra_info_file.close()

info_file.close()

# show the info file to user, for make sure
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "r")
print info_file.read()
info_file.close()

# create list file
list_file = open("%s/%s" % (dir_name, LIST_FILE_NAME), "w")

for part in file_map.keys():
    list_file.write("# %s\n" % part)
    for file in file_map[part]:
        list_file.write("%s\n" % file)

list_file.close()

# create final package
pkg_file = tarfile.open(pkg_file_name, "w:gz")

pkg_file.add("%s/%s" % (dir_name, LIST_FILE_NAME), LIST_FILE_NAME)
pkg_file.add("%s/%s" % (dir_name, INFO_FILE_NAME), INFO_FILE_NAME)

for part in file_map.keys():
    sys.stdout.write("adding files for %-10s: " % part)

    i = 0
    for file in file_map[part]:
        i += 1
        pkg_file.add("%s/%s" % (dir_name, file), file)

    print "%-4d files added" % i

pkg_file.close()

print "\nfont package %s finished, %d bytes in total." % \
        (pkg_file_name, os.stat(pkg_file_name)[stat.ST_SIZE])

